﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;
using System.IO;

namespace DX.engine
{
    public class Model
    {
        public string ModelName { get; set; }
        public CustomVertex.PositionColored[] vertices { get; set; }
        public short[] indices { get; set; }

        public Model()
        {
            indices = new short[0];
        }

        public void Export(string filename)
        {
            Engine.GetLoggingEngine().Log(string.Format("Exporting Model [{0}]...", ModelName));
            StreamWriter sw = new StreamWriter(filename);
            string s_name = string.Format("Name={0}", ModelName);
            string s_vertex = "\t{0}:{1},{2},{3}";
            string s_indices = string.Format("Indices={0}", string.Join(",", indices));
            string s_vertices = "Vertices=\r\n{0}";

            string[] verts = new string[vertices.Length];
            int i=0;
            foreach(CustomVertex.PositionColored pc in vertices)
                verts[i++] = string.Format(s_vertex, pc.Color, pc.X, pc.Y, pc.Z);
            s_vertices = string.Format(s_vertices, string.Join("\r\n",verts));
            sw.WriteLine(s_name);
            sw.WriteLine(s_vertices);
            sw.WriteLine(s_indices);
            sw.Flush();
            sw.Close();
            Engine.GetLoggingEngine().Log(string.Format("Exporting Model [{0}] complete!", ModelName));
        }

        public static Model Import(string filename)
        {
            string name = "(No Name)";
            List<CustomVertex.PositionColored> verts = new List<CustomVertex.PositionColored>();
            List<short> indices = new List<short>();

            StreamReader sr = new StreamReader(filename);
            name = sr.ReadLine().Split('=')[1];
            sr.ReadLine();  //Read Vertices line
            string line = string.Empty;
            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                if (line.Split('=')[0] == "Indices")
                    continue;
                string[] ColorAndPosition = line.Split(':');
                int color = int.Parse(ColorAndPosition[0]);
                string[] positions = ColorAndPosition[1].Split(',');
                float x = float.Parse(positions[0]);
                float y = float.Parse(positions[1]);
                float z = float.Parse(positions[2]);
                verts.Add(new CustomVertex.PositionColored(x, y, z, color));
            }
            string[] shawtz = line.Split('=')[1].Split(',');
            foreach (string s in shawtz)
                indices.Add(short.Parse(s));
            Model m = new Model();
            m.ModelName = name;
            m.vertices = verts.ToArray();
            m.indices = indices.ToArray();
            return m;
        }
    }
}
